import sys
import argparse
import re

def count_chars(content):
    """统计字符数"""
    return len(content)

def count_words(content):
    """统计单词数（以空白字符分割）"""
    return len(content.split())

def count_sentences(content):
    """使用正则表达式统计句子数，匹配句号、问号或感叹号后跟空白或文本结尾"""
    return len(re.findall(r'[.!?](?:\s|$)', content))

def main():
    parser = argparse.ArgumentParser(description="A command-line text counting tool.")
    parser.add_argument('file', help="The path to the input text file.")
    parser.add_argument('-c', '--chars', action='store_true', help="Count the number of characters.")
    parser.add_argument('-w', '--words', action='store_true', help="Count the number of words.")
    parser.add_argument('-s', '--sentences', action='store_true', help="Count the number of sentences.")
    parser.add_argument('--all', action='store_true', help="Show all statistics (characters, words, sentences).")
    args = parser.parse_args()

    # 读取txt文件内容
    try:
        with open(args.file, 'r', encoding='utf-8', errors='ignore') as f:
            content = f.read()
    except FileNotFoundError:
        print(f"Error: File not found at {args.file}", file=sys.stderr)
        sys.exit(1)

    # 根据用户指令 统计并输出结果
    if args.all or args.chars:
        print(f"Characters: {count_chars(content)}")
    if args.all or args.words:
        print(f"Words: {count_words(content)}")
    if args.all or args.sentences:
        print(f"Sentences: {count_sentences(content)}")

    # 如果没选任何选项，打印帮助说明
    if not (args.all or args.chars or args.words or args.sentences):
        parser.print_help()

if __name__ == '__main__':
    main()
